#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>

#define SHUOXIE_CONFIG_FILE "/etc/shuoxie.conf"
char ufdir[256];
char* getThemeDir()
{
    sprintf ( ufdir, "%s",  "/usr/share/shuoxie/theme");
    return ufdir;
}
char* getUserDir()
{
    sprintf(ufdir,"%s/.shuoxie",getenv("HOME"));
    g_mkdir_with_parents(ufdir,S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
    return ufdir;
}

char* getUserModelDir()
{
    sprintf(ufdir,"%s/.shuoxie/model",getenv("HOME"));    
    g_mkdir_with_parents(ufdir,S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
    return ufdir;
}
/***********************************
 * 
 * 除两端回车和空格
 * 
 * ********************************/
    void trim_string(char *str)  
    {  
        char *start, *end;  
        int len = strlen(str);  
      
        //去掉最后的换行符  
        if(str[len-1] == '\n')  
        {  
            len--;      //字符串长度减一  
            str[len] = 0;   //给字符串最后一个字符赋0，即结束符  
        }  
      
        //去掉两端的空格  
        start = str;        //指向首字符  
        end = str + len -1; //指向最后一个字符  
        while(*start && isspace(*start))  
            start++;    //如果是空格，首地址往前移一位，如果不是，则跳过该循环  
        while(*end && isspace(*end))  
            *end-- = 0; //如果是空格，末地址往前移一位，并赋结束符  
        strcpy(str, start); //把首地址还给str  
    }  
    
    /*
     *从配置文件中读取相应的值
     *输入参数：1，配置文件路径 2，匹配标记 3，输出存储空间
     *并且排除了空行，“=”前后无内容，无“=”的情况
     */
    int ReadConfig(char *conf_path,char *conf_name,char *config_buff)
    {
        char config_linebuf[256];        
        char *config_sign = "=";
        char *leave_line;
        int line=0;
        FILE *f;
        f = fopen(conf_path,"r");
        if(f == NULL)
        {
            printf("OPEN CONFIG FALID\n");
            return line;
        }
        fseek(f,0,SEEK_SET); 
        while(fgets(config_linebuf,256,f) != NULL)
        {   

            leave_line = NULL;
            leave_line = strstr(config_linebuf,conf_name);
            if(leave_line == NULL)                            //没有相关项
            {                
                continue;
            }
                      
            leave_line = NULL;
            leave_line = strstr(config_linebuf,config_sign);
            if(leave_line == NULL)                            //无"="的情况
            {
                
                continue;
            }            
            line=leave_line-config_linebuf;
            //printf("%s\n",leave_line+1);  
            if(line>1)
            {
                memset(config_buff,0,sizeof(config_buff));
                strncpy(config_buff,leave_line+1,strlen(leave_line)-1);  
                trim_string(config_buff);
                //printf("%slen:%d\n",config_buff,strlen(config_buff));
                
                break;
            }
            else
                line=0;
        }
        fclose(f);
        return line;
    }
    /*
     *添加修改文件（当配置文件中存在标记字段，则进行修改，若不存在则进行添加）
     *
     *输入参数：1，配置文件路径 2，匹配标记 3，替换或添加的内容
     *
     */
    void AddOrAltConfig(char *conf_path,char *conf_name,char *config_buff)
    {
        
        char config_linebuf[256];
        char newline[256];
        char line_name[40];
        char *config_sign = "=";
        char *leave_line;
        int b=0;
        
        FILE *f;
        f = fopen(conf_path,"a+");
        fclose(f);
        f = fopen(conf_path,"r+");
        if(f == NULL)
        {
            printf("OPEN CONFIG FALID\n");
            
                return ;
        }
        
        fseek(f,0,SEEK_SET);     
        while(fgets(config_linebuf,256,f) != NULL)
        {   
            leave_line = NULL;
            leave_line = strstr(config_linebuf,conf_name);
            if(leave_line == NULL)                            //没有相关项
            {                
                continue;
            }
            
            leave_line = NULL;
            leave_line = strstr(config_linebuf,config_sign);
            if(leave_line == NULL)                            //无"="的情况
            {
                
                continue;
            }
            
            memset(newline,0,sizeof(newline));
            strcat(newline,conf_name);
            strcat(newline,"=");
            strcat(newline,config_buff);
            strcat(newline,"\n");
            fseek(f,strlen(config_linebuf)*-1,SEEK_CUR);
            fwrite(newline,strlen(newline),1,f);           
            b=1;
            break;
        }
        if(b==0)
        {
            memset(newline,0,sizeof(newline));
            strcat(newline,conf_name);
            strcat(newline,"=");
            strcat(newline,config_buff);
            strcat(newline,"\n");            
            fwrite(newline,strlen(newline),1,f);  
        }
        fclose(f);
        
        
    }
    /*
     *删除配置文件内容（
     *
     *输入参数：1，配置文件路径 2，匹配标记 
     *
     */
   void DeleteConfig(char *conf_path,char *conf_name)
    {
        
        char config_linebuf[256];
        char line_name[40];
        char *config_sign = "=";
        char *leave_line;
        
        FILE *f;
        f = fopen(conf_path,"r+");
        if(f == NULL)
        {
            printf("OPEN CONFIG FALID\n");
            return ;
        }
        fseek(f,0,SEEK_END);
        long congig_lenth = ftell(f);
        char sum_buf[congig_lenth+2];
        memset(sum_buf,0,sizeof(sum_buf));
        fseek(f,0,SEEK_SET); 
        while(fgets(config_linebuf,256,f) != NULL)
        {   
            if(strlen(config_linebuf) < 3) //判断是否是空行
            {
                strcat(sum_buf,config_linebuf);
                continue;
            }
            leave_line = NULL;
            leave_line = strstr(config_linebuf,config_sign);
            if(leave_line == NULL)                            //去除无"="的情况
            {
                strcat(sum_buf,config_linebuf);
                continue;
            }
            int leave_num = leave_line - config_linebuf;
            memset(line_name,0,sizeof(line_name));
            strncpy(line_name,config_linebuf,leave_num);
            if(strcmp(line_name,conf_name) ==0)
            {
                
            }
            else
            {
                strcat(sum_buf,config_linebuf);
            }
            
            if(fgetc(f)==EOF)
            {
                break;  
            }
            fseek(f,-1,SEEK_CUR);
            memset(config_linebuf,0,sizeof(config_linebuf));
        }
        printf("---sum_buf---->%s<----------\n",sum_buf);
        remove(conf_path);
        fclose(f);
        FILE *fp;
        fp = fopen(conf_path,"w+");
        if(fp == NULL)
        {
            printf("OPEN CONFIG FALID\n");
            return;
        }
        fseek(fp,0,SEEK_SET);
        fputs(sum_buf,fp);
        fclose(fp);
    } 
    

int get_autoaddword()
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());
    int i=ReadConfig(file,"AutoAddWord",val);
    //printf("%s\n",val);
    if(i>0)
        return atoi(val);
    return 0;
}

void set_autoaddword(int i)
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());
    sprintf(val,"%d",i);
    AddOrAltConfig(file,"AutoAddWord",val);    
}
void set_bjcolor(GdkColor *bjcolor)
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());    
    sprintf(val,"%s",gdk_color_to_string(bjcolor));
    AddOrAltConfig(file,"BJColor",val);  
}
void set_hbcolor(GdkColor *hbcolor)
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());    
    sprintf(val,"%s",gdk_color_to_string(hbcolor));
    AddOrAltConfig(file,"HBColor",val);  
}
void get_bjcolor(GdkColor *color)
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());
    int i=ReadConfig(file,"BJColor",val);
    printf("%s\n",val);
    if(i>0){
        gdk_color_parse(val,color);
    }
    else{
         gdk_color_parse("#FFFFFF",color);
    }    
}
void get_hbcolor(GdkColor *color)
{
    char val[17];
    char file[256];
    sprintf(file,"%s/shuoxie.conf",getUserDir());
    int i=ReadConfig(file,"HBColor",val);
    //printf("%s\n",val);
    if(i>0){
        gdk_color_parse(val,color);
    }
    else{
         gdk_color_parse("#000000",color);
    }    
}
